#pragma once
#include <iostream>
#include <cstdlib>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

const std::string pathname = "/home/test/linux-system-and-network/shm";
const int proj_id = 0x11223344;
const int size = 4096;
const std::string filename = "fifo";

// 利用路径名和特定id获取key值
key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        exit(1);
    }
    return key;
}

// 将十进制转换成十六进制
std::string ToHex(int id)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", id);
    return buffer;
}

// 按照特定选项创建对应共享内存
int CreateShmHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        exit(2);
    }

    return shmid;
}

// 以644权限创建共享内存
int CreateShm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT | IPC_EXCL | 0644);
}

// 获取共享权限的shmid
int GetShm(key_t key)
{
    return CreateShmHelper(key, IPC_CREAT);
}

// 创建一个命名管道
bool MakeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if (n < 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }

    std::cout << "mkfifo success... read" << std::endl;
    return true;
}